# 测试WVP2数据库连接
Write-Host "=== 测试WVP2数据库连接 ===" -ForegroundColor Green

# 配置参数（根据你的application.yml）
$dbHost = "127.0.0.1"
$dbPort = "3306"
$dbName = "wvp2"
$dbUser = "root"
$dbPassword = "root123"

Write-Host "配置信息：" -ForegroundColor Yellow
Write-Host "  数据库主机: $dbHost" -ForegroundColor White
Write-Host "  数据库端口: $dbPort" -ForegroundColor White
Write-Host "  数据库名称: $dbName" -ForegroundColor White
Write-Host "  用户名: $dbUser" -ForegroundColor White
Write-Host "  密码: $dbPassword" -ForegroundColor White

# 1. 检查MySQL服务
Write-Host "`n1. 检查MySQL服务状态..." -ForegroundColor Yellow
try {
    $mysqlService = Get-Service -Name "*mysql*" -ErrorAction SilentlyContinue
    if ($mysqlService) {
        foreach ($service in $mysqlService) {
            $status = if($service.Status -eq 'Running'){'✓ 运行中'}else{'❌ 已停止'}
            $color = if($service.Status -eq 'Running'){'Green'}else{'Red'}
            Write-Host "  $($service.Name): $status" -ForegroundColor $color
        }
    } else {
        Write-Host "  ❌ 未找到MySQL服务" -ForegroundColor Red
    }
} catch {
    Write-Host "  检查服务时出错: $($_.Exception.Message)" -ForegroundColor Red
}

# 2. 检查端口
Write-Host "`n2. 检查MySQL端口..." -ForegroundColor Yellow
try {
    $netstat = netstat -an | findstr ":3306"
    if ($netstat) {
        Write-Host "  ✓ MySQL正在监听端口3306" -ForegroundColor Green
        $netstat | ForEach-Object { Write-Host "    $_" -ForegroundColor Gray }
    } else {
        Write-Host "  ❌ MySQL未监听端口3306" -ForegroundColor Red
    }
} catch {
    Write-Host "  检查端口时出错: $($_.Exception.Message)" -ForegroundColor Red
}

# 3. 创建Java连接测试
Write-Host "`n3. 创建数据库连接测试..." -ForegroundColor Yellow

$javaTest = @"
import java.sql.*;

public class TestWVP2Connection {
    public static void main(String[] args) {
        String url = "jdbc:mysql://127.0.0.1:3306/?useSSL=false&allowPublicKeyRetrieval=true&serverTimezone=PRC";
        String dbUrl = "jdbc:mysql://127.0.0.1:3306/wvp2?useSSL=false&allowPublicKeyRetrieval=true&serverTimezone=PRC";
        String username = "root";
        String password = "root123";
        
        try {
            // 测试基本连接
            System.out.println("正在测试MySQL连接...");
            Class.forName("com.mysql.cj.jdbc.Driver");
            Connection conn = DriverManager.getConnection(url, username, password);
            System.out.println("✓ MySQL连接成功!");
            
            // 检查数据库是否存在
            Statement stmt = conn.createStatement();
            ResultSet rs = stmt.executeQuery("SHOW DATABASES LIKE 'wvp2'");
            if (rs.next()) {
                System.out.println("✓ 数据库 'wvp2' 存在");
                
                // 测试连接到wvp2数据库
                conn.close();
                conn = DriverManager.getConnection(dbUrl, username, password);
                System.out.println("✓ 成功连接到wvp2数据库");
                
                // 检查表
                stmt = conn.createStatement();
                rs = stmt.executeQuery("SHOW TABLES");
                System.out.println("数据库中的表:");
                boolean hasTables = false;
                while (rs.next()) {
                    System.out.println("  - " + rs.getString(1));
                    hasTables = true;
                }
                if (!hasTables) {
                    System.out.println("  ❌ 数据库中没有表，需要执行初始化脚本");
                }
            } else {
                System.out.println("❌ 数据库 'wvp2' 不存在，需要创建");
            }
            
            conn.close();
            System.out.println("✓ 连接测试完成");
            
        } catch (ClassNotFoundException e) {
            System.out.println("❌ MySQL驱动未找到: " + e.getMessage());
        } catch (SQLException e) {
            System.out.println("❌ 数据库连接失败: " + e.getMessage());
            if (e.getMessage().contains("Access denied")) {
                System.out.println("  可能的原因: 用户名或密码错误");
            } else if (e.getMessage().contains("Connection refused")) {
                System.out.println("  可能的原因: MySQL服务未启动或端口错误");
            }
        } catch (Exception e) {
            System.out.println("❌ 其他错误: " + e.getMessage());
        }
    }
}
"@

$javaTest | Out-File -FilePath "TestWVP2Connection.java" -Encoding UTF8
Write-Host "  ✓ 已创建连接测试文件: TestWVP2Connection.java" -ForegroundColor Green

Write-Host "`n=== 解决方案 ===" -ForegroundColor Cyan

Write-Host "`n步骤1: 确保MySQL服务运行" -ForegroundColor Yellow
Write-Host "如果MySQL服务未运行，请启动它：" -ForegroundColor White
Write-Host "  方法1: Windows服务管理器 -> 启动MySQL服务" -ForegroundColor Gray
Write-Host "  方法2: 命令行执行 'net start mysql'" -ForegroundColor Gray

Write-Host "`n步骤2: 验证数据库连接" -ForegroundColor Yellow
Write-Host "编译并运行连接测试：" -ForegroundColor White
Write-Host "  javac -cp target/classes TestWVP2Connection.java" -ForegroundColor Gray
Write-Host "  java -cp .;target/classes TestWVP2Connection" -ForegroundColor Gray

Write-Host "`n步骤3: 创建数据库和表" -ForegroundColor Yellow
Write-Host "使用MySQL客户端执行初始化脚本：" -ForegroundColor White
Write-Host "  mysql -h 127.0.0.1 -P 3306 -u root -proot123 < fix_database_wvp2.sql" -ForegroundColor Gray
Write-Host "或者使用图形化工具（phpMyAdmin、Navicat等）执行 fix_database_wvp2.sql" -ForegroundColor Gray

Write-Host "`n步骤4: 检查Redis连接" -ForegroundColor Yellow
Write-Host "确保Redis服务运行并且密码正确：" -ForegroundColor White
Write-Host "  Redis密码: RedisData@123456." -ForegroundColor Gray
Write-Host "  如果Redis没有设置密码，请修改application.yml中的Redis密码配置" -ForegroundColor Gray

Write-Host "`n步骤5: 重新启动WVP应用" -ForegroundColor Yellow
Write-Host "完成数据库初始化后，重新启动应用程序" -ForegroundColor White

Write-Host "`n当前需要执行的文件：" -ForegroundColor Green
Write-Host "  - fix_database_wvp2.sql (数据库初始化脚本)" -ForegroundColor White
Write-Host "  - TestWVP2Connection.java (连接测试程序)" -ForegroundColor White

Read-Host "`n按回车键退出"
